<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="题目类型" prop="questionType">
        <el-select
          v-model="queryParams.questionType"
          placeholder="请选择题目类型"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="dict in question_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="题目难度" prop="difficultyLevel">
        <el-select
          v-model="queryParams.difficultyLevel"
          placeholder="请选择题目难度"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="dict in difficulty_level"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否标记" prop="marked">
        <el-select
          v-model="queryParams.marked"
          placeholder="请选择是否标记"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="dict in sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否正确" prop="correct">
        <el-select
          v-model="queryParams.correct"
          placeholder="请选择是否正确"
          clearable
          style="width: 120px"
        >
          <el-option
            v-for="dict in sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="questionList"
    >
      <el-table-column label="题目类型" align="center" prop="questionType">
        <template #default="scope">
          <dict-tag :options="question_type" :value="scope.row.questionType" />
        </template>
      </el-table-column>
      <el-table-column label="题目内容" align="center" prop="questionContent" />
      <el-table-column label="题目难度" align="center" prop="difficultyLevel">
        <template #default="scope">
          <dict-tag
            :options="difficulty_level"
            :value="scope.row.difficultyLevel"
          />
        </template>
      </el-table-column>
      <el-table-column label="主题" align="center" prop="subject" />
      <el-table-column label="题目分值" align="center" prop="score" />
      <el-table-column label="是否正确" align="center" prop="correct">
        <template #default="scope">
          <span v-if="scope.row.correct === null || scope.row.correct === undefined">未答题</span>
          <span v-else-if="scope.row.correct === 0">错误</span>
          <span v-else>正确</span>
        </template>
      </el-table-column>
      <el-table-column label="是否标记" align="center" prop="marked">
        <template #default="scope">
          <span v-if="scope.row.marked === null || scope.row.marked === undefined || scope.row.marked === 0">未标记</span>
          <span v-else>已标记</span>
        </template>
      </el-table-column>
      
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="180"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="doParctice(scope.row)"
            v-hasPermi="['business:practice:do']"
            >答题</el-button
          >
          <el-button
            v-if="!scope.row.marked"
            link
            type="primary"
            icon="Star"
            @click="handleMark(scope.row)"
            v-hasPermi="['business:practice:mark']"
            >标记</el-button
          >
          <el-button
            v-else
            link
            type="warning"
            icon="StarFilled"
            @click="handleUnmark(scope.row)"
            v-hasPermi="['business:practice:unMark']"
            >取消标记</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 答题对话框 -->
    <el-dialog :title="'答题 - ' + practiceForm.questionType" v-model="practiceOpen" width="800px" append-to-body>
      <el-form ref="practiceFormRef" :model="practiceForm" :rules="practiceRules" label-width="100px">
        <el-form-item label="题目类型">
          <dict-tag :options="question_type" :value="practiceForm.questionType" />
        </el-form-item>
        <el-form-item label="题目内容">
          <div v-html="practiceForm.questionContent"></div>
        </el-form-item>
        <el-form-item label="题目难度">
          <dict-tag :options="difficulty_level" :value="practiceForm.difficultyLevel" />
        </el-form-item>
        <el-form-item label="主题">
          <span>{{ practiceForm.subject }}</span>
        </el-form-item>
        <el-form-item label="分值">
          <span>{{ practiceForm.score }}分</span>
        </el-form-item>
        
        <!-- 单选题选项 -->
        <el-form-item v-if="practiceForm.questionType === 'single-choice'" label="选项">
          <el-radio-group v-model="practiceForm.userAnswer">
            <el-radio 
              v-for="option in practiceForm.choiceOptionList" 
              :key="option.id" 
              :label="option.optionLetter"
            >
              {{ option.optionLetter }}. {{ option.optionContent }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 多选题选项 -->
        <el-form-item v-if="practiceForm.questionType === 'multiple-choice'" label="选项">
          <el-checkbox-group v-model="practiceForm.userAnswer">
            <el-checkbox 
              v-for="option in practiceForm.choiceOptionList" 
              :key="option.id" 
              :label="option.optionLetter"
            >
              {{ option.optionLetter }}. {{ option.optionContent }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- 填空题答案 -->
        <el-form-item v-if="practiceForm.questionType === 'blank-filling'" label="答案">
          <el-input 
            v-model="practiceForm.userAnswer" 
            type="text" 
            placeholder="请输入答案"
          />
        </el-form-item>

        <!-- 编程题答案 -->
        <el-form-item v-if="practiceForm.questionType === 'coding'" label="答案">
          <el-input 
            v-model="practiceForm.userAnswer" 
            type="textarea" 
            :rows="10"
            placeholder="请输入代码"
          />
        </el-form-item>
 
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAnswer">提交答案</el-button>
          <el-button type="warning" @click="markQuestion">标记题目</el-button>
          <el-button @click="practiceOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Question">
import {
  myListQuestion,
  getQuestion,
  submitPractice, markQuestionApi, unmarkQuestionApi
} from "@/api/business/question";

const { proxy } = getCurrentInstance();
const { question_type, sys_common_status, difficulty_level, sys_yes_no,exam_question_type } =
  proxy.useDict(
    "question_type",
    "sys_common_status",
    "difficulty_level",
    "sys_yes_no",
    "exam_question_type"
  );

const questionList = ref([]);
const choiceOptionList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    questionType: null,
    questionContent: null,
    difficultyLevel: null,
    auditStatus: null,
    marked:null,
    correct:null
  },
  rules: {
    questionType: [
      { required: true, message: "题目类型不能为空", trigger: "change" },
    ],
    questionContent: [
      { required: true, message: "题目内容不能为空", trigger: "blur" },
    ],
    difficultyLevel: [
      { required: true, message: "题目难度不能为空", trigger: "change" },
    ],
    score: [{ required: true, message: "题目分值不能为空", trigger: "blur" }],
    auditStatus: [
      { required: true, message: "审核状态不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 答题相关数据
const practiceOpen = ref(false);
const practiceFormRef = ref();
const practiceForm = ref({
  id: null,
  questionType: null,
  questionContent: null,
  difficultyLevel: null,
  subject: null,
  score: null,
  userAnswer: null,
  choiceOptionList: []
});

const practiceRules = {
  userAnswer: [
    { required: true, message: "请输入答案", trigger: "blur" }
  ]
};

/** 查询题目列表 */
function getList() {
  loading.value = true;
  myListQuestion(queryParams.value).then((response) => {
    questionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}


// 表单重置
function reset() {
  form.value = {
    id: null,
    type:'practice',
    questionType: null,
    questionContent: null,
    difficultyLevel: null,
    correctAnswer: null,
    answerExplanation: null,
    subject: null,
    score: null,
    source: null,
    auditStatus: null,
    auditOpinion: null,
    createTime: null,
    updateTime: null,
  };
  choiceOptionList.value = [];
  proxy.resetForm("questionRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


/** 答题按钮操作 */
function doParctice(row) {
  console.log("题目数据:", row);
  practiceForm.value = {
    id: row.id,
    questionType: row.questionType,
    questionContent: row.questionContent,
    difficultyLevel: row.difficultyLevel,
    subject: row.subject,
    score: row.score,
    userAnswer: row.questionType === 'multiple-choice' ? [] : null,
    choiceOptionList: row.optionList || []
  };
  console.log("初始化后的表单:", practiceForm.value);
  practiceOpen.value = true;
}

/** 提交答案 */
function submitAnswer() {
  practiceFormRef.value.validate(valid => {
    if (valid) {
      let userAnswer = practiceForm.value.userAnswer;
      
      // 如果是多选题，将数组转换为逗号分隔的字符串
      if (practiceForm.value.questionType === 'multiple-choice' && Array.isArray(userAnswer)) {
        userAnswer = userAnswer.join(',');
      }
      
      const data = {
        questionId: practiceForm.value.id,
        questionType: practiceForm.value.questionType,
        answer: userAnswer
      };
      console.log("提交的答案数据:", data);
      submitPractice(data).then(response => {
        proxy.$modal.msgSuccess("提交成功");
        practiceOpen.value = false;
        getList();
      });
    }
  });
}

/** 标记题目 */
function handleMark(row) {
  proxy.$modal.confirm('是否确认标记该题目？').then(function() {
    markQuestionApi(row.id).then(response => {
      proxy.$modal.msgSuccess("标记成功");
      getList();
    });
  });
}

/** 取消标记 */
function handleUnmark(row) {
  proxy.$modal.confirm('是否确认取消标记该题目？').then(function() {
    unmarkQuestionApi(row.id).then(response => {
      proxy.$modal.msgSuccess("取消标记成功");
      getList();
    });
  });
}

getList();
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
